package com.distribute.portal.interceptor;

import java.lang.reflect.Method;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.distribute.portal.annotation.Token;
import com.distribute.portal.dao.JedisClient;

public class TokenInterceptor extends HandlerInterceptorAdapter {
	@Autowired JedisClient jedisClient;
	@Value("${REDIS_TOKEN}")
	private String REDIS_TOKEN;
	
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            Token annotation = method.getAnnotation(Token.class);
            if (annotation != null) {
                boolean needSaveSession = annotation.save();
                if (needSaveSession) {
                	/**/
                	String uuId =  UUID.randomUUID().toString();
                	jedisClient.set(REDIS_TOKEN, uuId);
                    request.setAttribute("redis_token",uuId);
                }
                boolean needRemoveSession = annotation.remove();
                if (needRemoveSession) {
                    if (isRepeatSubmit(request)) {
                    	response.sendRedirect("error-repeat.html");
                        return false;
                    }
                    jedisClient.del(REDIS_TOKEN);
                }
            }
            return true;
        } else {
            return super.preHandle(request, response, handler);
        }
    }

    private boolean isRepeatSubmit(HttpServletRequest request) {
        String serverToken = (String) jedisClient.get(REDIS_TOKEN);
        if (serverToken == null) {
            return true;
        }
        String clinetToken = request.getParameter("redis_token");
        if (clinetToken == null) {
            return true;
        }
        if (!serverToken.equals(clinetToken)) {
            return true;
        }
        return false;
    }
}